package gosnoopers.fr;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import lazy_listview.JSONfunctions;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class GmapActivity extends FragmentActivity implements OnClickListener, OnMapClickListener, OnMarkerDragListener{

	public static final String KEY_ID_VICTIM = "victim";
	public LatLng POINT_1;
	private Marker point_1;
	private GoogleMap gMap;
	private double lng, lat;
	String id_victim;
	private ImageView mImgDone;
	private List<Address> addresses;
	private static Geocoder gcd;
	private ProgressBar mProBarWaiting;

	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.map_post);
        TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
        text_view_landing_page_header.setText("Victime Gmap");
        
		init();
		setValueForMap();
		setEventForMember();
	}

	public void init() {
    	lat = 48.8534100;
		lng = 2.3488000;
		POINT_1 = new LatLng(lat, lng);
		
		gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
		addresses = new ArrayList<Address>();
		
		try {
			addresses = gcd.getFromLocation(lat, lng, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map_post)).getMap();
		id_victim = getIntent().getStringExtra(KEY_ID_VICTIM);
		mImgDone = (ImageView) findViewById(R.id.image_done);
		mProBarWaiting = (ProgressBar) findViewById(R.id.probar_waiting);
		mProBarWaiting.setVisibility(View.GONE);
		mImgDone.setVisibility(View.VISIBLE);
		
		
	}
	
	public void setValueForMap() {
		if (gMap != null) {
			MarkerOptions marker = new MarkerOptions().position(POINT_1).title(addresses.get(0).getLocality()).draggable(true);
			// Changing marker icon
			marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.mk));
			point_1 = gMap.addMarker(marker);
		}
		gMap.setOnMarkerDragListener(this);
		CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(POINT_1, 10);	
		gMap.animateCamera(cameraUpdate);
	}

	public void setEventForMember() {
		mImgDone.setOnClickListener(this);
	}
	
	@Override
	public void onMapClick(LatLng point) {
	}

	@Override
	public void onMarkerDrag(Marker marker) {
	}

	@Override
	public void onMarkerDragEnd(Marker marker) {
		
		try {
			LatLng position = marker.getPosition();
			lat = position.latitude;
			lng = position.longitude;
			
			addresses = gcd.getFromLocation(lat, lng, 1);
			Toast.makeText(getApplicationContext(), "You are "+addresses.get(0).getLocality(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onMarkerDragStart(Marker marker) {
	}
	
	/**
	 * asyncTask upload to server id - lat - lng
	 */
	
	protected String getParamPost() {
		StringBuffer url = new StringBuffer("id=");
		url.append(id_victim);
		url.append("&lat=");
		url.append(lat);
		url.append("&longtitude=");
		url.append(lng);
		url.append("&address=");
		url.append(addresses.get(0).getLocality());
		System.out.println("AAAAAAAAAAAAAA "+url.toString());
		return url.toString();
	}
	public static String messagePostPhoto = "";
	private class UploadToServer extends AsyncTask<String, Void, Boolean> {
		
		private String urlPost;
		private JSONObject jsonDataResult;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			urlPost = "http://gosnoopers.com/victimes/app/updateLL?uuid="+id_victim;
			Log.d("Gmap Post: ", ""+params[0]);
			jsonDataResult = JSONfunctions.executeUrlWithOption(true, urlPost, params[0], false);
			try {
				Log.d("Gmap activity: ", "JSON: "+jsonDataResult);
				messagePostPhoto = jsonDataResult.getString("message");
				return jsonDataResult.getBoolean("error");
			} catch (Exception e) {
				return true;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result == false) {
				Intent goToHomePage = new Intent(getApplicationContext(), HomePage.class);
                startActivity(goToHomePage);
			}else{
				
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage(messagePostPhoto)
				.setCancelable(false)
				.setNegativeButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_done:
			mImgDone.setVisibility(View.GONE);
			mProBarWaiting.setVisibility(View.VISIBLE);
			new UploadToServer().execute(getParamPost());
			break;
		default:
			break;
		}
		
	}
	final Context context = this;
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	        // your code
	    	
	    	
	    		
	    		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage("Are you sure go back?")
				.setCancelable(false)
				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
						Intent goToNextActivity = new Intent(getApplicationContext(), HomePage.class);
			               startActivity(goToNextActivity);
						
					}
				  })
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
	    	
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
}